package com.laxcen.basiclib.core.db;

import android.util.Log;

import com.laxcen.basiclib.core.db.table.DbColumn;
import com.laxcen.basiclib.utils.LogUtil;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *  数据库 预处理的数据
 *
 * Create by 游德禄 on 2020-5-26
 */
public class DbPreview {


    /**
     *  当第一次安装APP
     *  创建数据库时 执行这里的代码
     */
    public static void init(){

    }

    /**
     *  检查所有数据库表字段是否需要更新
     *  如果要要更新会自动更新字段
     *  此代码需开一个耗时线程去执行
     *  比如版本更新时
     */
    public static void updateDbFields(){
        Map<String, List<String>> tabColumn = new HashMap<>();
        Map<String, List<DbColumn>> claColumn = new HashMap<>();
        for (int i = 0; i < DbHelper.getTables().size(); i++) {
            Class cla = DbHelper.getTables().get(i);
            String claName = cla.getName();
            try {
                Class<?> c = Class.forName(claName);
                if (DbHelper.tableIsExist(c)) {
                    List<String> column = DbHelper.getTableCloumn(c);
                    //    LogUtil.e("tableCloumn",DbHelper.getTableName(c)+"->"+JsonMananger.beanToJsonStr(column));
                    String tableName = DbHelper.getTableName(c);
                    //设置表结构
                    tabColumn.put(tableName, column);
                    //获取类字段及类型，并转化成sqlite的类型
                    List<DbColumn> clas = new ArrayList<>();
                    Field[] f = cla.getDeclaredFields();
                    for (Field field : f) {
                        String fildName = field.getName();
                        char firstChar = fildName.charAt(0);
                        if (Character.isUpperCase(firstChar)) {
                            continue;
                        }
                        if (fildName.equals("serialVersionUID")
                                || fildName.equals("id")
                                || fildName.equals("$change")) {
                            continue;
                        }

                        String fildType = field.getType().toString();
                        //过滤掉接口类型
                        if (fildType.startsWith("interface")) {
                            continue;
                        }
                        if (fildType.startsWith("class")) {
                            if (fildType.contains(".")) {
                                fildType = fildType.substring(fildType.lastIndexOf(".") + 1);
                            }
                            fildType = fildType.toLowerCase();
                        }
                        //类型转换
                        switch (fildType) {
                            case "string":
                                fildType = "TEXT";
                                break;
                            case "int":
                            case "integer":
                            case "long":
                            case "boolean":
                            case "date":
                                fildType = "INTEGER";
                                break;
                            case "float":
                            case "double":
                                fildType = "REAL";
                                break;
                            default:
                                continue;
                        }

                        DbColumn beanColumn = new DbColumn();
                        beanColumn.setName(fildName);
                        beanColumn.setType(fildType);

                        clas.add(beanColumn);
                    }
                    claColumn.put(tableName, clas);
                }
            } catch (Exception e) {
                LogUtil.e("dbInitError", e.getMessage());
            }
        }
        //去除已存在的字段
        for (String key : tabColumn.keySet()) {
            for (String cKey : claColumn.keySet()) {
                if (key.equals(cKey)) {
                    List<String> column = tabColumn.get(key);
                    List<DbColumn> beanColumns = claColumn.get(cKey);
                    for (int i = 0; i < column.size(); i++) {
                        for (int j = 0; j < beanColumns.size(); j++) {
                            if (column.get(i).equals(beanColumns.get(j).getName())) {
                                claColumn.get(cKey).remove(j);
                            }
                        }
                    }
                }
            }
        }

        //更新新增的字段
        for (String key : claColumn.keySet()) {
            List<DbColumn> columns = claColumn.get(key);
            if (claColumn != null && columns.size() > 0) {
                for (int i = 0; i < columns.size(); i++) {
                    String sql = "ALTER TABLE " + key + " ADD COLUMN " + columns.get(i).getName() + " " + columns.get(i).getType();
                    Log.i("addNewColumn", sql);
                    DbHelper.exec_nonquery(sql);
                    try {
                        Thread.sleep(10);
                    }catch (Exception e){}
                }

            }
        }
    }
}
